#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#define SER_PORT 5001
#define IP_ADDR "172.16.2.55"
int main() // node.js
{

    // 1.创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        perror("create socket error");
    }

    struct in_addr ipaddr;
    inet_pton(AF_INET, IP_ADDR, &ipaddr);
    struct sockaddr_in addr;
    addr.sin_addr = ipaddr;
    addr.sin_family = AF_INET;
    addr.sin_port = SER_PORT;
    // 2.绑定地址和端口
    int ret = bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
    if (ret == -1)
    {
        perror("bind error");
    }
    // 3.监听请求
    ret = listen(sockfd, 2);
    if (ret == -1)
    {
        perror("listen error");
    }
    // 4.接收请求  accept函数会阻塞进程，直到接收到 来自客户端的请求
    printf("服务器端等待客户端连接请求:\n");
    int newFd = accept(sockfd, NULL, NULL);
    if (newFd == -1)
    {
        perror("accept error");
    }
    // 5.接收客户端发来的数据
    char buf[100];
    read(newFd, buf, sizeof(buf));
    printf("接收到消息：%s\n", buf);
    printf("向客户端发送消息：heiheihei\n");
    write(newFd, "heiheihei", 9);
    // 6.关闭连接
    close(newFd);
}